package com.example.cosplay.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
@RequestMapping("/images")
@Slf4j
public class ImageController {

    @GetMapping("/{filename:.+}")
    public ResponseEntity<Resource> getImage(@PathVariable String filename) {
        // 尝试从默认下载目录获取图片
        return getImageFromPath("E:\\autoImg", filename);
    }
    
    @GetMapping("/{directory}/{filename:.+}")
    public ResponseEntity<Resource> getImageFromCustomDir(
            @PathVariable String directory,
            @PathVariable String filename) {
        // 尝试从自定义目录获取图片
        return getImageFromPath(directory, filename);
    }
    
    private ResponseEntity<Resource> getImageFromPath(String directory, String filename) {
        try {
            Path filePath = Paths.get(directory, filename);
            File file = filePath.toFile();
            
            if (!file.exists()) {
                log.error("图片不存在: {}", filePath);
                return ResponseEntity.notFound().build();
            }
            
            // 检测文件类型
            String contentType = Files.probeContentType(filePath);
            if (contentType == null) {
                contentType = MediaType.IMAGE_JPEG_VALUE; // 默认为JPEG
            }
            
            Resource resource = new FileSystemResource(file);
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .body(resource);
        } catch (IOException e) {
            log.error("获取图片时出错", e);
            return ResponseEntity.badRequest().build();
        }
    }
} 